import json
import random
import time
from settings import *
import pymongo
from furl import furl
from fastapi import FastAPI, Request
import requests
from auth.init_auth_info import jumei_info
from settings import *

app = FastAPI()
client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DATABASE]
auth_accounts = []

@app.get('/')
def get_params(request: Request):
    '''
    监控回调地址，获取auth_code ,app_id
    :param request:
    :return:
    '''
    url = request.url
    f = furl(url)
    authorization_code = f.args['authorization_code']
    app_id = int(f.args['state'])
    message = update_auth_info(authorization_code, app_id)
    return message



def update_auth_info(auth_code, app_id):
    '''
    保存token
    :param auth_code:
    :param app_id:
    :return:
    '''
    app_info = db[COL_AUTH_INFO].find({'app_id': app_id})
    if app_info is None:
        message = '授权参数保存失败，请检查参数后重试！'
    else:
        auth_info = get_token(auth_code, app_id)
        db[COL_AUTH_INFO].update_one({'app_id': auth_info['app_id']}, {'$set': auth_info},True)
        message = '授权成功!'
        get_auth_accounts(auth_info['app_id'])
    return message


def api_get_auth_accounts(auth_params, page=1):
    '''
    从接口获取账户id
    :param auth_params:
    :param page:
    :return:
    '''

    common_parameters = {
        'access_token': auth_params['access_token'],
        'timestamp': int(time.time()),
        'nonce': str(time.time()) + str(random.randint(0, 999999)),
    }
    parameters = {
        "page": page,
        "page_size": 100,
    }
    parameters.update(common_parameters)
    for k in parameters:
        if type(parameters[k]) is not str:
            parameters[k] = json.dumps(parameters[k])
    resp = requests.get(ADVERTISER_INFO, params=parameters)
    result = json.loads(resp.text)['data']['list']
    page_size = len(result)
    if page_size >= 100:
        page += 1
        api_get_auth_accounts(auth_params, page)
    global auth_accounts
    auth_accounts += result
    return auth_accounts
def get_auth_accounts(app_id):
    '''
    将结果保存到数据库
    :return:
    '''
    auth_info = db[COL_AUTH_INFO].find({'app_id':app_id})
    for auth_params in auth_info:
        print('params:', auth_params)
        accounts = api_get_auth_accounts(auth_params)

        print('账户个数为:', len(accounts))
        print('账户个数为:',accounts)
        for account in accounts:
            item = {}
            item['account_id'] = account.get("account_id")
            item['status'] = 1
            item['app_id'] = auth_params['app_id']
            item['access_token'] = auth_params['access_token']
            item['refresh_token'] = auth_params['refresh_token']

            db[COL_AUTH_ACCOUNTS].update_one({'account_id': item.get('account_id')}, {'$set': item}, True)
        auth_accounts.clear()

def get_token(auth_code, app_id):
    '''
    获取 token
    :param auth_code: 授权码
    :param app_id: 应用id
    :return:
    '''
    params = {
        'client_id': app_id,
        'client_secret': jumei_info['secret'],
        'grant_type': 'authorization_code',
        'authorization_code': auth_code,
        'redirect_uri': 'http://61.174.246.71'
    }
    resp = requests.get(GET_TOKEN, params=params)

    data = json.loads(resp.text)['data']
    print('data:',data)
    result = {
        'app_id':data.get('authorizer_info').get('account_uin'),
        'access_token': data.get('access_token'),
        'secret': jumei_info['secret'],
        'account_name':data.get('authorizer_info').get('account_name'),
        'refresh_token': data.get('refresh_token'),
        'access_token_expires_in': data.get('access_token_expires_in'),
        'refresh_token_expires_in': data.get('refresh_token_expires_in'),
    }
    return result



